import Cocoa
import SwiftUI
import Combine

// 任务栏窗口类
class TaskbarWindow: NSWindow {
    let taskbarHeight: CGFloat = 44
    
    init(screen: NSScreen, screenIndex: Int) {
        let screenFrame = screen.frame
        let windowFrame = NSRect(
            x: screenFrame.minX,
            y: screenFrame.minY,  // 在屏幕底部
            width: screenFrame.width,
            height: taskbarHeight
        )
        
        super.init(
            contentRect: windowFrame,
            styleMask: [.borderless],
            backing: .buffered,
            defer: false
        )
        
        // 确保窗口在正确的屏幕上
        self.setFrame(windowFrame, display: true)
        
        // print("📺 在屏幕 \(screenIndex) 创建任务栏: \(windowFrame)")
        
        self.level = .floating
        self.isOpaque = false
        self.hasShadow = false
        self.ignoresMouseEvents = false
        self.canHide = false
        self.collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
        
        // 设置背景色
        self.backgroundColor = NSColor.controlBackgroundColor.withAlphaComponent(0.95)
        
        // 创建内容视图
        let contentView = TaskbarContentView(screenIndex: screenIndex)
        self.contentView = NSHostingView(rootView: contentView)
        
        // 确保窗口始终可见
        self.orderFront(nil)
    }
}

// 任务栏内容视图
@available(macOS 10.15, *)
struct TaskbarContentView: View {
    @ObservedObject private var windowManager = WindowManager.shared
    let screenIndex: Int
    
    var windowsForThisScreen: [WindowInfo] {
        // Windows风格：每个显示器的任务栏都显示所有窗口
        return windowManager.windows
    }
    
    var body: some View {
        HStack(spacing: 2) {
            ForEach(windowsForThisScreen.indices, id: \.self) { index in
                let window = windowsForThisScreen[index]
                TaskbarItem(
                    windowInfo: window,
                    windowManager: windowManager
                ) {
                    windowManager.activateWindow(window)
                } onDoubleClick: {
                    windowManager.toggleWindowMinimization(window)
                }
            }
            
            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.clear)
    }
}

// 任务栏项目视图
@available(macOS 10.15, *)
struct TaskbarItem: View {
    let windowInfo: WindowInfo
    let windowManager: WindowManager
    let onClick: () -> Void
    let onDoubleClick: () -> Void
    
    @State private var isHovered = false
    @State private var clickCount = 0
    
    private func appIconImage() -> NSImage? {
        if let path = windowInfo.appIconPath {
            // 用 NSWorkspace 获取 .app 的图标
            let img = NSWorkspace.shared.icon(forFile: path)
            if img.isValid { return img }
        }
        return nil
    }
    
    var body: some View {
        HStack(spacing: 8) {
            // 应用图标
            if let nsImage = appIconImage() {
                Image(nsImage: nsImage)
                    .resizable()
                    .frame(width: 20, height: 20)
            } else {
                // 默认图标 - 使用NSImage而不是SF Symbols
                if let defaultIcon = NSImage(named: NSImage.applicationIconName) {
                    Image(nsImage: defaultIcon)
                        .resizable()
                        .frame(width: 20, height: 20)
                        .opacity(0.5)
                } else {
                    Rectangle()
                        .fill(Color.secondary)
                        .frame(width: 20, height: 20)
                        .cornerRadius(4)
                }
            }
            
            // 窗口标题
            Text(windowInfo.displayName)
                .font(.system(size: 13))
                .lineLimit(1)
                .truncationMode(.tail)
                .foregroundColor(windowInfo.isMinimized ? .secondary : .primary)
        }
        .padding(.horizontal, 8)
        .padding(.vertical, 4)
        .background(
            RoundedRectangle(cornerRadius: 6)
                .fill(backgroundColor)
                .shadow(radius: isHovered ? 2 : 0)
        )
        .overlay(
            RoundedRectangle(cornerRadius: 6)
                .stroke(borderColor, lineWidth: windowInfo.isMinimized ? 1 : 0)
        )
        .onHover { hovering in
            withAnimation(.easeInOut(duration: 0.1)) {
                isHovered = hovering
            }
        }
        .onTapGesture(count: 1) {
            handleClick()
        }
        .contextMenu {
            Button("关闭窗口") {
                closeWindow()
            }
            Button(windowInfo.isMinimized ? "恢复窗口" : "最小化") {
                windowManager.toggleWindowMinimization(windowInfo)
            }
        }
    }
    
    private var backgroundColor: Color {
        if isHovered {
            return Color.accentColor.opacity(0.3)
        } else if windowInfo.isMinimized {
            return Color.secondary.opacity(0.1)
        } else {
            return Color.primary.opacity(0.1)
        }
    }
    
    private var borderColor: Color {
        windowInfo.isMinimized ? .secondary : .clear
    }
    
    private func handleClick() {
        clickCount += 1
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            if clickCount == 1 {
                onClick()
                // 激活后短延时刷新窗口状态
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    WindowManager.shared.refreshWindows()
                }
            } else if clickCount >= 2 {
                onDoubleClick()
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    WindowManager.shared.refreshWindows()
                }
            }
            clickCount = 0
        }
    }
    
    private func closeWindow() {
        let app = AXUIElementCreateApplication(windowInfo.processId)
        var windowsRef: CFTypeRef?
        
        if AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &windowsRef) == .success,
           let windows = windowsRef as? [AXUIElement] {
            
            for window in windows {
                var titleRef: CFTypeRef?
                if AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef) == .success,
                   let title = titleRef as? String,
                   title == windowInfo.windowTitle {
                    
                    // 尝试关闭窗口
                    var closeButtonRef: CFTypeRef?
                    if AXUIElementCopyAttributeValue(window, kAXCloseButtonAttribute as CFString, &closeButtonRef) == .success,
                       CFGetTypeID(closeButtonRef) == AXUIElementGetTypeID() {
                        let closeButton = closeButtonRef as! AXUIElement
                        AXUIElementPerformAction(closeButton, kAXPressAction as CFString)
                    }
                    
                    break
                }
            }
        }
    }
}

// 移除不需要的扩展